import json

from PyQt6.QtCore import pyqtSignal
from PyQt6.QtWidgets import QHBoxLayout, QWidget
from qfluentwidgets import FluentWindow, FluentIcon, PrimaryPushButton, TransparentToolButton, InfoBar, \
    LineEdit, setFont, FluentIcon as FIF

from common import AppPluginBase, FileTypeIcon
from components import BaseWidget, HighlighterTextEdit, BaseScrollArea


class JsonFormatView(BaseWidget):
    returned = pyqtSignal()

    title = 'json 格式化'
    description = '该插件用于格式化 JSON 字符串'
    is_shortcut = True
    object_name = 'JsonFormatView'
    icon = FileTypeIcon.JSON

    def __init__(self, parent=None):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout()
        self.returnBtn = TransparentToolButton(FluentIcon.RETURN, self)
        self.separatorsLineEdit = LineEdit(self)
        self.formatJsonBtn = PrimaryPushButton(FluentIcon.CODE, '格式化 JSON', self)

        self.jsonTextEdit = self.creatTextEdit()

        self.__initUi()

    def __initUi(self):
        self.setObjectName(self.object_name)
        self.separatorsLineEdit.setPlaceholderText(
            '请输入 JSON 分隔符(自定义分隔, 最多 2 个字符, 使用英文半角逗号分隔, 如: " :,; ")')
        self.jsonTextEdit.setPlaceholderText('请输入 JSON 字符串')
        setFont(self.jsonTextEdit, 20)

        self.horizontalLayout.addWidget(self.returnBtn)
        self.horizontalLayout.addWidget(self.separatorsLineEdit, 1)
        self.horizontalLayout.addWidget(self.formatJsonBtn)
        self.topLayout.addLayout(self.horizontalLayout)

        self.returnBtn.clicked.connect(self.returned)
        self.formatJsonBtn.clicked.connect(self.formatJson)

        data = {
            "name": "Alice",
            "age": 30,
            "city": "New York",
            "skills": ["Python", "Java", "C++"]
        }
        self.jsonTextEdit.setText(str(data))

    def formatJson(self):
        text = self.jsonTextEdit.toPlainText()
        separators = self.separatorsLineEdit.text().strip().split(',')
        if len(separators) > 2:
            InfoBar.error('分隔符错误', '最多只能输入 2 个字符的分隔符, 使用英文半角逗号分隔, 如: " :,; ",请重新输入',
                          duration=3000, parent=self.window())
            return
        elif len(separators) == 2:
            separators = tuple(separators)
        else:
            separators = None
        try:
            formatted_text = json.dumps(eval(text), indent=4, ensure_ascii=False, separators=separators)
            self.jsonTextEdit.setJson(formatted_text)
        except Exception:
            InfoBar.error('JSON 格式错误', '请输入正确的 JSON 字符串', duration=3000, parent=self.window())

    def creatTextEdit(self):
        widget = QWidget(self)
        layout = QHBoxLayout(widget)
        textEdit = HighlighterTextEdit(widget)
        textEdit.setAcceptRichText(False)
        textEdit.setTabChangesFocus(False)
        layout.setContentsMargins(36, 0, 36, 10)
        layout.addWidget(textEdit)
        self.setWidget(widget)
        return textEdit
